#!/bin/bash

set -e

VERSION="241122.1552"

function deploy {
    local APP="$1"
    local DEPLOY="$APP"
    local SVC="$APP"
    local NS="$2"
    local CONFIG_MAP_NAME="$APP-configmap"

    function k8s {
        minikube kubectl -- --namespace=$NS "$@"
    }

    echo "=> Create or Update configmap: $CONFIG_MAP_NAME"
    if k8s get configmap "$CONFIG_MAP_NAME" --template="{{.metadata.name}}"
    then
        echo
        echo " > Found and try to replace config map $CONFIG_MAP_NAME"
        k8s replace configmap "$CONFIG_MAP_NAME" -f "./$APP/k8s/configmap.yaml"
    else
        echo " > Not found and try to create config map $CONFIG_MAP_NAME"
        k8s apply -f "./$APP/k8s/configmap.yaml"
    fi

    echo "=> Try to deploy: $DEPLOY"
    if k8s get deploy "$DEPLOY" --template="{{.metadata.name}}"
    then
        echo
        echo " > Found and try to replace deployment $DEPLOY"
        k8s replace -f "$APP/k8s/deployment.yaml" --force=true
    else
        echo " > Not found and try to create deployment $DEPLOY"
        k8s apply  -f "$APP/k8s/deployment.yaml"
    fi

    echo "=> Try to service: $SVC"
    k8s apply -f "$APP/k8s/service.yaml" --force=true
}

modules=(user gateway)
for mod in "${modules[@]}"
do
  image="navia-$mod:$VERSION"
  echo "=> Try to load image ($image) into minikube "
  minikube image load "$image"
  deploy "navia-$mod" xyzwps-dev
done

